package com.eorchis.module.trainingneeds.service.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileItem;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.stereotype.Service;

import com.eorchis.core.basedao.dao.IDaoSupport;
import com.eorchis.core.basedao.entity.IBaseEntity;
import com.eorchis.core.service.impl.AbstractBaseService;

import com.eorchis.module.basedata.domain.BaseData;
import com.eorchis.module.classcourse.ui.commond.ClassCourseValidCommond;
import com.eorchis.module.classuser.dao.IClassUserDao;
import com.eorchis.module.classuser.ui.commond.ClassUserQueryCommond;
import com.eorchis.module.trainingneeds.dao.IQuestionnaireDao;
import com.eorchis.module.trainingneeds.domain.PreviewQuestionnaireBean;
import com.eorchis.module.trainingneeds.domain.QueryQuestionBankBean;
import com.eorchis.module.trainingneeds.domain.QueryQuestionnaireBean;
import com.eorchis.module.trainingneeds.domain.QuerySurveyObjectBean;
import com.eorchis.module.trainingneeds.domain.QuestionBank;
import com.eorchis.module.trainingneeds.domain.QuestionBankOption;
import com.eorchis.module.trainingneeds.domain.QuestionOptionBean;
import com.eorchis.module.trainingneeds.domain.QuestionTypeBean;
import com.eorchis.module.trainingneeds.domain.Questionnaire;
import com.eorchis.module.trainingneeds.domain.QuestionnaireQuestion;
import com.eorchis.module.trainingneeds.domain.QuestionnaireSurveyObject;
import com.eorchis.module.trainingneeds.service.IQuestionnaireService;
import com.eorchis.module.trainingneeds.ui.commond.QuestionBankQueryCommond;
import com.eorchis.module.trainingneeds.ui.commond.QuestionBankValidCommond;
import com.eorchis.module.trainingneeds.ui.commond.QuestionnaireQueryCommond;
import com.eorchis.module.trainingneeds.ui.commond.QuestionnaireQuestionTypeValidCommond;
import com.eorchis.module.trainingneeds.ui.commond.QuestionnaireSurveyObjectQueryCommond;
import com.eorchis.module.trainingneeds.ui.commond.QuestionnaireSurveyObjectValidCommond;
import com.eorchis.module.trainingneeds.ui.commond.QuestionnaireValidCommond;
import com.eorchis.module.user.domain.User;
import com.eorchis.utils.DateUtil;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: QuestionnaireServiceImpl<br>
 * Description: 培训需求问卷表管理业务接口实现<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author HuangTF
 * @createDate 2014-02-07
 * @version $Revision$
 */
// 声明本类为Server实现类，声明bean名称
@Service(value = "com.eorchis.module.trainingneeds.service.impl.QuestionnaireServiceImpl")
public class QuestionnaireServiceImpl extends AbstractBaseService implements IQuestionnaireService {

	@Resource(name = "com.eorchis.module.trainingneeds.dao.impl.QuestionnaireDaoImpl")
	private IQuestionnaireDao questionnaireDao;

	@Resource(name = "com.eorchis.module.classuser.dao.impl.ClassUserDaoImpl")
	private IClassUserDao classUserDao;
	
	@Override
	public IDaoSupport getDaoSupport() {
		return questionnaireDao;
	}

	@Override
	@SuppressWarnings("unchecked")
	public QuestionnaireValidCommond toCommond(IBaseEntity entity) {
		return new QuestionnaireValidCommond((Questionnaire)entity);
	}

	/**
	 * 判断培训需求调查问卷名称是否重复
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-7
	 */
	@Override
	public boolean isRepeatName(String questionnaireName) throws Exception
	{
		return questionnaireDao.isRepeatName(questionnaireName);
	}
	/**
	 * 发布撤销培训需求调查问卷
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-7
	 */
	@Override
	public String publishQuestionnaire(QuestionnaireQueryCommond queryCommond) throws Exception
	{
		if(queryCommond.getPublishState().equals(Questionnaire.IS_PUBLISH_Y))
		{
			if(!questionnaireDao.isPublish(queryCommond))
			{
				return "问卷必须设置试题和调查对象后才能发布！";
			}
		}
		else
		{
			String[] questionnaireIds=queryCommond.getSearchQuestionnaireIds();
			for(String id: questionnaireIds)
			{
				QuestionnaireValidCommond c=this.find(id);
				Date start=DateUtil.changeDate0H0m0s0ms(new Date());
				Date end=DateUtil.changeDate23H59m59s999ms(new Date());
				if(!c.getBeginDate().after(end)&&!c.getEndDate().before(start))
//				if(!c.getBeginDate().after(new Date())&&!c.getEndDate().before(new Date()))
				{
					return "已开始的调查问卷，不能撤销发布！";
				}
			}
		}
		if(questionnaireDao.publishQuestionnaire(queryCommond)>0)
		{
			return "操作成功";
		}
		else
		{
			return "操作失败";
		}
	}
	/**
	 * 逻辑删除培训需求调查问卷
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-7
	 */
	@Override
	public void delQuestionnaire(QuestionnaireQueryCommond queryCommond) throws Exception
	{
		questionnaireDao.updateState(Questionnaire.class, queryCommond.getSearchQuestionnaireIds(), Questionnaire.IS_ACTIVE_N);
//		questionnaireDao.delAll(queryCommond);
//		questionnaireDao.u
		
		//删除问卷试题关联
		//删除问卷试题题型
		//删除问卷调查对象
	}
	/**
	 * 查询已选调查对象(指定人员)
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-8
	 */
	@Override
	public List<QuerySurveyObjectBean> querySurveyObjectSelected(QuestionnaireSurveyObjectQueryCommond queryCommond) throws Exception
	{
		queryCommond.setSurveyObjectType(QuestionnaireSurveyObject.SURVEY_TYPE_USER);//查询类型为指定人员的
		return questionnaireDao.querySurveyObjectSelected(queryCommond);
	}
	/**
	 * 查询未选调查对象(指定人员)
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-8
	 */
	@Override
	public List<QuerySurveyObjectBean> querySurveyObjectNoSelected(QuestionnaireSurveyObjectQueryCommond queryCommond) throws Exception
	{
		//设置单位路径
		ClassUserQueryCommond commond=new ClassUserQueryCommond();
		commond.setSearchDepId(queryCommond.getDepId());
		queryCommond.setTreePath(classUserDao.findDepTreePath(commond).get(0).getTreepath());
		
		return questionnaireDao.querySurveyObjectNoSelected(queryCommond);
	}
//	/**
//	 * 更新问卷调查对象类型
//	 * @param queryCommond
//	 * @return
//	 * @throws Exception
//	 * @author HuangTF
//	 * @createDate 2014-5-27
//	 */
//	@Override
//	public void updateSurveyObjectType(QuestionnaireSurveyObjectQueryCommond queryCommond) throws Exception
//	{
//		questionnaireDao.updateSurveyObjectType(queryCommond);
//	}
	/**
	 * 更新问卷表调查对象类型
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-5-27
	 */
	@Override
	public void updateSurveyObjectTypeQuestionnaire(QuestionnaireSurveyObjectQueryCommond queryCommond) throws Exception
	{
		questionnaireDao.updateSurveyObjectTypeQuestionnaire(queryCommond);
	}
	/**
	 * 删除问卷调查对象类型信息
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-5-27
	 */
	@Override
	public void delSurveyObjectType(QuestionnaireSurveyObjectQueryCommond queryCommond) throws Exception
	{
		questionnaireDao.delSurveyObjectType(queryCommond);
	}
	/**
	 * 删除问卷调查对象
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-7
	 */
	@Override
	public void delSurveyObject(QuestionnaireSurveyObjectQueryCommond queryCommond) throws Exception
	{
		questionnaireDao.delete(QuestionnaireSurveyObject.class, queryCommond.getQuestionnaireSurveyObjectIds());
	}
	/**
	 * 查询题库试题列表
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-17
	 */
	@Override
	public List<QueryQuestionBankBean> queryQuestionBank(QuestionBankQueryCommond queryCommond) throws Exception
	{
		queryCommond.setActiveState(QuestionBank.IS_ACTIVE_Y);
		
		List<QueryQuestionBankBean> beanList=questionnaireDao.queryQuestionBank(queryCommond);
		
		List<String> questionIdList=questionnaireDao.isCanDel(queryCommond);
		//页面删除状态
		//1：已被选为调查问卷试题且已发布，不允许删除！
		//2：已被选为调查问卷试题，确定要删除？
		//3：您确定要删除这些信息吗?
		for(QueryQuestionBankBean bean: beanList)
		{
			if(bean.getIsSelected().intValue()==1)
				bean.setIsSelected(2);
			if(questionIdList.contains(bean.getQuestionId()))
			{
				bean.setIsSelected(1);
			}
		}
		
		return beanList;
	}
	/**
	 * 查询试题信息
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-17
	 */
	@Override
	public QueryQuestionBankBean queryQuestionInfo(QuestionBankValidCommond commond) throws Exception
	{
		QueryQuestionBankBean bean=questionnaireDao.queryQuestionInfo(commond);
		if(PropertyUtil.objectNotEmpty(bean.getWordNum()))
		{
			bean.setWordNum(bean.getWordNum()/2);
		}
		if(PropertyUtil.objectNotEmpty(bean.getQuestionOptionStr()))
		{
			List<QuestionOptionBean> optionList=new ArrayList<QuestionOptionBean>();
			String[] options=bean.getQuestionOptionStr().split(",");
			for(String option: options)
			{
				QuestionOptionBean qo=new QuestionOptionBean();
				qo.setOptionNum(option.substring(0, option.indexOf("-")));
				if(PropertyUtil.objectNotEmpty(option.substring(2, option.indexOf("-")+2))){
					qo.setObjectiveTopic(Integer.parseInt(option.substring(2, option.indexOf("-")+2)));
				}
				qo.setOptionName(option.substring(option.indexOf("-")+3));
				optionList.add(qo);
			}
			Collections.sort(optionList, new Comparator<QuestionOptionBean>() {
				@Override
				public int compare(QuestionOptionBean o1, QuestionOptionBean o2) 
				{
					return o1.getOptionNum().compareTo(o2.getOptionNum());
				}
			});
			bean.setQuestionOption(optionList);
		}
		return bean;
	}
	/**
	 * 判断试题题干是否重复
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-17
	 */
	@Override
	public boolean isRepeatQuestionName(QuestionBankValidCommond commond) throws Exception
	{
		return questionnaireDao.isRepeatQuestionName(commond);
	}
	/**
	 * 新增题库试题
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-17
	 */
	@Override
	public String addQuestionBank(QuestionBankValidCommond commond) throws Exception
	{
		QuestionBank questionBank=(QuestionBank) commond.toEntity();
		if(PropertyUtil.objectNotEmpty(questionBank.getWordNum()))
		{
			questionBank.setWordNum(questionBank.getWordNum()*2);
		}
//		else
//		{
//			questionBank.setWordNum(0);
//		}
		//试题题型
		BaseData questionType=new BaseData();
		questionType.setDataCode(commond.getQuestionType());
		
		questionBank.setQuestionType(questionType);
		questionnaireDao.save(questionBank);
		
		if(PropertyUtil.objectNotEmpty(commond.getOptions()))
		{
			String[] options=null;
			if(commond.getQuestionType().equals(QuestionBank.QUESTION_DUO)){
				options=commond.getOptionsCollection();
			}else{
				options=commond.getOptions();
			}
			
			for(int i=0;i<options.length;i++)
			{
				if(PropertyUtil.objectNotEmpty(options[i]))
				{
					String[] nq=options[i].split("@sp@");
					if(PropertyUtil.objectNotEmpty(nq[0])){
						QuestionBankOption questionBankOption=new QuestionBankOption();
						questionBankOption.setQuestionBank(questionBank);
						questionBankOption.setOptionNum(String.valueOf((char)(i+(int)('A'))));//选项排序
						if(commond.getQuestionType().equals(QuestionBank.QUESTION_DUO)){
							if(PropertyUtil.objectNotEmpty(nq[0])){
								questionBankOption.setOptionName(nq[0]);
								if(PropertyUtil.objectNotEmpty(nq[1])){
									questionBankOption.setObjectiveTopic( Integer.parseInt(nq[1]));
								}else{
									questionBankOption.setObjectiveTopic(2);
								}
							}
								
							
						}else{
							questionBankOption.setOptionName(options[i]);
							questionBankOption.setObjectiveTopic(2);
						}
						//questionBankOption.setObjectiveTopic(options[i]);
						questionnaireDao.save(questionBankOption);
					}
				}
			}
		}
		return "添加成功";
	}
	/**
	 * 更新题库试题
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-17
	 */
	@Override
	public String updateQuestionBank(QuestionBankValidCommond commond) throws Exception
	{
		questionnaireDao.delQuestionOption(commond);//删除试题选项
		if(PropertyUtil.objectNotEmpty(commond.getWordNum()))
		{
			commond.setWordNum(commond.getWordNum()*2);
		}
		//更新试题信息
		questionnaireDao.updateQuestionBank(commond);
		//如果是选择题，添加试题选项
		if(PropertyUtil.objectNotEmpty(commond.getOptions()))
		{
			QuestionBank questionBank=new QuestionBank();
			questionBank.setQuestionId(commond.getQuestionId());
			
			String[] options=null;
			if(commond.getQuestionType().equals(QuestionBank.QUESTION_DUO)){
				options=commond.getOptionsCollection();
			}else{
				options=commond.getOptions();
			}
			
			for(int i=0;i<options.length;i++)
			{
				if(PropertyUtil.objectNotEmpty(options[i]))
				{
					String[] nq=options[i].split("@sp@");
					if(PropertyUtil.objectNotEmpty(nq[0])){
						QuestionBankOption questionBankOption=new QuestionBankOption();
						questionBankOption.setQuestionBank(questionBank);
						//questionBankOption.setOptionName(options[i]);
						questionBankOption.setOptionNum(String.valueOf((char)(i+(int)('A'))));//选项排序
						if(commond.getQuestionType().equals(QuestionBank.QUESTION_DUO)){
							
							if(PropertyUtil.objectNotEmpty(nq[0])){
								questionBankOption.setOptionName(nq[0]);
								if(PropertyUtil.objectNotEmpty(nq[1])){
									questionBankOption.setObjectiveTopic( Integer.parseInt(nq[1]));
								}else{
									questionBankOption.setObjectiveTopic(2);
								}
							}
								
							
						}else{
							questionBankOption.setOptionName(options[i]);
							questionBankOption.setObjectiveTopic(2);
						}
						questionnaireDao.save(questionBankOption);
					}
				}
			}
		}
		return "更新成功";
	}
//	/**
//	 * 删除题库试题
//	 * @param queryCommond
//	 * @return
//	 * @throws Exception
//	 * @author HuangTF
//	 * @createDate 2014-2-17
//	 */
//	@Override
//	public boolean delQuestionBank(QuestionBankQueryCommond queryCommond) throws Exception
//	{
//		//判断是否可以删除
//		if(questionnaireDao.isCanDel(queryCommond.getQuestionIds()))
//		{
//			queryCommond.setActiveState(QuestionBank.IS_ACTIVE_N);
//			questionnaireDao.updateQuestionBank(queryCommond);
//			
//			return true;
//		}
//		else
//		{
//			return false;
//		}
//	}
	/**
	 * 删除题库试题
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-17
	 */
	@Override
	public void delQuestionBank(QuestionBankQueryCommond queryCommond) throws Exception
	{
		queryCommond.setActiveState(QuestionBank.IS_ACTIVE_N);
		//逻辑删除试题
		questionnaireDao.updateQuestionActiveState(queryCommond);
		
//		questionnaireDao.updateState(QuestionBank.class, queryCommond.getQuestionIds(), QuestionBank.IS_ACTIVE_N);
		//删除问卷试题关联
		questionnaireDao.delQuestionnaireQuestion(queryCommond);
		
	}
	/**
	 * 查询问卷表已设置题型
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-18
	 */
	public List<QuestionTypeBean> queryQuestionType(QuestionBankQueryCommond queryCommond) throws Exception
	{
		List<String> typeList=questionnaireDao.queryQuestionType(queryCommond);//问卷已选题型
		List<String> allType=questionnaireDao.queryAllQuestionType();//全部题型
//		String[] types={QuestionBank.QUESTION_DAN,QuestionBank.QUESTION_DUO,QuestionBank.QUESTION_WEN};
		
		List<QuestionTypeBean> questionTypeList=new ArrayList<QuestionTypeBean>();
		for(int i=0;i<allType.size();i++)
		{
			QuestionTypeBean typeBean=new QuestionTypeBean();
			typeBean.setTypeCode(allType.get(i));
			if(typeList.contains(allType.get(i)))
			{
				typeBean.setIsSelected(QuestionTypeBean.IS_SELECTED_Y);
			}
			else
			{
				typeBean.setIsSelected(QuestionTypeBean.IS_SELECTED_N);
			}
			questionTypeList.add(typeBean);
		}
		
		return questionTypeList;
	}
	/**
	 * 问卷设置试题时查询已选题库试题
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-18
	 */
	@Override
	public List<QueryQuestionBankBean> queryQuestionSelected(QuestionBankQueryCommond queryCommond) throws Exception
	{
		return questionnaireDao.queryQuestionSelected(queryCommond);
	}
	/**
	 * 问卷设置试题时查询未选题库试题
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-18
	 */
	public List<QueryQuestionBankBean> queryQuestionNoSelected(QuestionBankQueryCommond queryCommond) throws Exception
	{
		
		queryCommond.setActiveState(QuestionBank.IS_ACTIVE_Y);
		return questionnaireDao.queryQuestionNoSelected(queryCommond);
	}
	/**
	 * 新增问卷试题
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-18
	 */
	@Override
	public void addQuestionnaireQuestion(QuestionBankQueryCommond queryCommond) throws Exception
	{
		if(PropertyUtil.objectNotEmpty(queryCommond.getQuestionIds()))
		{
			String[] ids=queryCommond.getQuestionIds();
			QuestionBank qb=this.getDaoSupport().find(QuestionBank.class, ids[0]);
			queryCommond.setQuestionType(qb.getQuestionType().getDataCode());
			//获取当前问卷所选题型的最大排序序号
			int maxOrderNum=questionnaireDao.queryQuestionnaireQuestionMaxOrder(queryCommond);
			
			for(int i=0;i<ids.length;i++)
			{
				QuestionnaireQuestion questionnaireQuestion=new QuestionnaireQuestion();
				
				Questionnaire questionnaire=new Questionnaire();
				questionnaire.setQuestionnaireId(queryCommond.getQuestionnaireId());
				
				QuestionBank questionBank=new QuestionBank();
				questionBank.setQuestionId(ids[i]);
				
				questionnaireQuestion.setQuestionnaire(questionnaire);
				questionnaireQuestion.setQuestionBank(questionBank);
				questionnaireQuestion.setIsMust(QuestionnaireQuestion.IS_MUST_Y);//问卷试题默认必填
				
				questionnaireQuestion.setOrderNum(maxOrderNum+1+i);
				
				questionnaireDao.save(questionnaireQuestion);
			}
		}
	}
	/**
	 * 更新问卷试题排序及是否必填
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-18
	 */
	@Override
	public void updateQuestionnaireQuestion(QuestionBankQueryCommond queryCommond) throws Exception
	{
		QuestionnaireQuestion questionnaireQuestion=questionnaireDao.find(QuestionnaireQuestion.class, queryCommond.getQuestionnaireQuestionId());
		
		if(PropertyUtil.objectNotEmpty(queryCommond.getOrderNum()))
		{
			questionnaireQuestion.setOrderNum(queryCommond.getOrderNum());
		}
		if(PropertyUtil.objectNotEmpty(queryCommond.getIsMust()))
		{
			questionnaireQuestion.setIsMust(queryCommond.getIsMust());
		}
		questionnaireDao.update(questionnaireQuestion);
	}
	/**
	 * 保存问卷试题题型
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-18
	 */
	@Override
	public void saveQuestionnaireQuestionType(QuestionnaireQuestionTypeValidCommond commond) throws Exception
	{
		questionnaireDao.save(commond.toEntity());
	}
	/**
	 * 删除问卷试题
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-2-18
	 */
	@Override
	public void delQuestionnaireQuestion(QuestionBankQueryCommond queryCommond) throws Exception
	{
		QuestionnaireQuestion questionnaireQuestion=this.getDaoSupport().find(QuestionnaireQuestion.class, queryCommond.getQuestionnaireQuestionIds()[0]);
		queryCommond.setQuestionnaireId(questionnaireQuestion.getQuestionnaire().getQuestionnaireId());
		queryCommond.setQuestionType(questionnaireQuestion.getQuestionBank().getQuestionType().getDataCode());
		queryCommond.setPage(-1);
		
		this.getDaoSupport().delete(QuestionnaireQuestion.class, queryCommond.getQuestionnaireQuestionIds());
		//删除后排序
//		this.sortQuestionAfterDel(queryCommond);
	}
	/**
	 * 删除问卷试题后更新试题排序
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-09-12
	 */
	@Override
	public void sortQuestionAfterDel(QuestionBankQueryCommond queryCommond) throws Exception
	{
		List<QueryQuestionBankBean> beanList=questionnaireDao.queryQuestionSelected(queryCommond);
		if(beanList.size()>0)
		{
			List<String> questionnaireQuestionIdList=new ArrayList<String>();
			for(QueryQuestionBankBean bean: beanList)
			{
				questionnaireQuestionIdList.add(bean.getQuestionnaireQuestionId());
			}
			questionnaireDao.sortQuestionAfterDel(questionnaireQuestionIdList);
		}
	}
	/**
	 * 问卷查看列表,查看已结束问卷调查情况
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-4-29
	 */
	@Override
	public List<QueryQuestionnaireBean> findEndQuestionnaireList(QuestionnaireQueryCommond queryCommond) throws Exception
	{
		queryCommond.setActiveState(Questionnaire.IS_ACTIVE_Y);
		return questionnaireDao.findEndQuestionnaireList(queryCommond);
	}
	/**
	 * 查看参与问卷调查的人员详情
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-4-29
	 */
	public List<QuerySurveyObjectBean> findSurveyUserInfo(QuestionnaireSurveyObjectQueryCommond queryCommond) throws Exception
	{
		return questionnaireDao.findSurveyUserInfo(queryCommond);
	}
	/**
	 * 查看已结束问卷主观题调查情况
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-4-29
	 */
	@Override
	public List<QueryQuestionBankBean> endQuestionnaireSubjective(QuestionBankQueryCommond queryCommond) throws Exception
	{
		queryCommond.setQuestionType("'"+QuestionBank.QUESTION_WEN+"'");
		return questionnaireDao.endQuestionnaireResult(queryCommond);
	}
	/**
	 * 查看已结束问卷客观题调查情况
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-4-29
	 */
	@Override
	public List<QueryQuestionBankBean> endQuestionnaireObjective(QuestionBankQueryCommond queryCommond) throws Exception
	{
		queryCommond.setQuestionType("'"+QuestionBank.QUESTION_DAN+"','"+QuestionBank.QUESTION_DUO+"'");
		return questionnaireDao.endQuestionnaireResult(queryCommond);
	}
	/**
	 * 预览问卷信息
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-5-28
	 */
	@Override
	public PreviewQuestionnaireBean queryQuestionnaireQuestion(QuestionnaireValidCommond commond) throws Exception
	{
		List<QueryQuestionBankBean> list=questionnaireDao.queryQuestionnaireQuestion(commond);
		for(QueryQuestionBankBean bean: list)
		{
			if(!PropertyUtil.objectNotEmpty(bean.getQuestionOptionStr()))
				continue;
			List<QuestionOptionBean> optionList=new ArrayList<QuestionOptionBean>();
			String[] options=bean.getQuestionOptionStr().split(",");
			for(String option: options)
			{
				QuestionOptionBean qo=new QuestionOptionBean();
				qo.setOptionNum(option.substring(0, option.indexOf("-")));
				qo.setOptionName(option.substring(option.indexOf("-")+1));
				qo.setObjectiveTopic(bean.getObjectiveTopic());
				optionList.add(qo);
			}
			Collections.sort(optionList, new Comparator<QuestionOptionBean>() {
				@Override
				public int compare(QuestionOptionBean o1, QuestionOptionBean o2) 
				{
					return o1.getOptionNum().compareTo(o2.getOptionNum());
				}
			});
			bean.setQuestionOption(optionList);
		}
		List<QueryQuestionBankBean> singleChoice=new ArrayList<QueryQuestionBankBean>();//单选题集合 
		List<QueryQuestionBankBean> multipleChoice=new ArrayList<QueryQuestionBankBean>();//多选题集合 
		List<QueryQuestionBankBean> essayQuestion=new ArrayList<QueryQuestionBankBean>();//问答题集合 
		for(QueryQuestionBankBean bean: list)
		{
			//
			if(PropertyUtil.objectNotEmpty(commond.getUser())&&PropertyUtil.objectNotEmpty(commond.getUser().getUserId()))
			{
				if(!QuestionBank.QUESTION_WEN.equals(bean.getQuestionType()))
				{
					String selectOption=bean.getQuestionAnswer();
					
					List<QuestionOptionBean> optionList=bean.getQuestionOption();
					for(QuestionOptionBean qo: optionList)
						if(selectOption.contains(qo.getOptionNum()))
							qo.setSelect(true);
				}
			}
			
			if(QuestionBank.QUESTION_DAN.equals(bean.getQuestionType()))
				singleChoice.add(bean);
			else
				if(QuestionBank.QUESTION_DUO.equals(bean.getQuestionType()))
					multipleChoice.add(bean);
				else
					if(QuestionBank.QUESTION_WEN.equals(bean.getQuestionType()))
						essayQuestion.add(bean);
		}
		Questionnaire q=this.getDaoSupport().find(Questionnaire.class, commond.getEntityID());
		PreviewQuestionnaireBean previewQuestionnaireBean=new PreviewQuestionnaireBean();
		
		previewQuestionnaireBean.setQuestionnaireId(commond.getQuestionnaireId());
		previewQuestionnaireBean.setSingleChoice(singleChoice);
		previewQuestionnaireBean.setMultipleChoice(multipleChoice);
		previewQuestionnaireBean.setEssayQuestion(essayQuestion);
		previewQuestionnaireBean.setQuestionnaireName(q.getQuestionnaireName());
		previewQuestionnaireBean.setQuestionnaireExplain(q.getQuestionnaireExplain());
		
		return previewQuestionnaireBean;
	}
	/**
	 * 导入Excel试题到题库
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-11-06
	 */
	@Override
	public String importExcelQuestion(FileItem item,User user) throws Exception
	{
		InputStream inputStream=null;
		POIFSFileSystem fileSystem=null;
		HSSFWorkbook workbook=null;
		
		inputStream=item.getInputStream();
		fileSystem = new POIFSFileSystem(inputStream);
		workbook = new HSSFWorkbook(fileSystem);
		
		List<QuestionBankValidCommond> commondList=new ArrayList<QuestionBankValidCommond>();
		try
		{
			for(int i=0;i<workbook.getNumberOfSheets();i++)
			{
				if(PropertyUtil.objectNotEmpty(workbook.getSheetAt(i)))
					commondList.addAll(this.createImportQuestion(workbook.getSheetAt(i)));
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return "导入失败，请参照正确的模板导入试题！";
		}
//		int questionNum=commondList.size();//试题总数
		//去除题库已有试题
		Map<String, List<String>> typeNameMap=new HashMap<String, List<String>>();
		for(QuestionBankValidCommond commond: commondList)
		{
			if(!typeNameMap.containsKey(commond.getQuestionType()))
			{
				typeNameMap.put(commond.getQuestionType(), new ArrayList<String>());
			}
			typeNameMap.get(commond.getQuestionType()).add(commond.getQuestionName());
		}
		typeNameMap=questionnaireDao.queryRepeatNameQuestion(typeNameMap);
		if(PropertyUtil.objectNotEmpty(typeNameMap))
		{
			Iterator<QuestionBankValidCommond> it=commondList.iterator();
			while(it.hasNext())
			{
				QuestionBankValidCommond commond=it.next();
				
				if(typeNameMap.containsKey(commond.getQuestionType()))
				{
					if(typeNameMap.get(commond.getQuestionType()).contains(commond.getQuestionName()))
					{
						it.remove();
					}
				}
			}
		}
		//去重结束
//		int repeatQuestionNum=questionNum-commondList.size();//重复试题数
		for(QuestionBankValidCommond commond: commondList)
		{
			commond.setUser(user);
//			this.addQuestionBank(commond);
			commond.setQuestionId(UUID.randomUUID().toString().replace("-", ""));
			if(PropertyUtil.objectNotEmpty(commond.getWordNum()))
			{
				commond.setWordNum(commond.getWordNum()*2);
			}
		}
		//批量添加试题
		boolean flag=true;
		if(commondList.size()>0)
		{
			flag=questionnaireDao.addBatchQuestion(commondList);
			if(flag)
			{
				//批量添加试题选项
				Iterator<QuestionBankValidCommond> it=commondList.iterator();
				while(it.hasNext())
				{
					if(!PropertyUtil.objectNotEmpty(it.next().getOptions()))
					{
						it.remove();
					}
				}
				if(commondList.size()>0)
					flag=questionnaireDao.addBatchQuestionOptions(commondList);
			}
		}
		if(flag)
			return "导入成功！";
//			return "导入成功！共导入 "+(questionNum-repeatQuestionNum)+" 道试题，重复试题 "+repeatQuestionNum+" 道";
		else
			return "导入失败，请参照正确的模板导入试题！";
			
	}
	/**
	 * 转换Excel为试题对象
	 * @param queryCommond
	 * @return
	 * @throws Exception
	 * @author HuangTF
	 * @createDate 2014-11-06
	 */
	private List<QuestionBankValidCommond> createImportQuestion(HSSFSheet sheet) throws Exception
	{
		List<QuestionBankValidCommond> commondList=new ArrayList<QuestionBankValidCommond>();
		String sheetName=sheet.getSheetName();
		if(sheetName.equals("单选题")||sheetName.equals("多选题"))
		{
			for(int i=2;i<sheet.getLastRowNum();i++)
			{
				if(PropertyUtil.objectNotEmpty(sheet.getRow(i)))
				{
					HSSFRow row = sheet.getRow(i);
					if(!PropertyUtil.objectNotEmpty(row.getCell(0))||getCellValue(row.getCell(0)).toString().equals(""))
					{
						continue;
					}
					QuestionBankValidCommond commond=new QuestionBankValidCommond();
					commond.setQuestionName(getCellValue(row.getCell(0)).toString());
					if(sheetName.equals("单选题"))
					{
						commond.setQuestionType("danxt");
					}
					else
						if(sheetName.equals("多选题"))
						{
							commond.setQuestionType("duoxt");
						}
					String options="";
					for(int j=1;j<row.getLastCellNum();j++)
					{
						HSSFCell cell=(HSSFCell) row.getCell(j);
						if(PropertyUtil.objectNotEmpty(cell)&&!getCellValue(cell).toString().equals(""))
						{
							options+=getCellValue(cell).toString()+",";
						}
					}
					if(!options.equals(""))
					{
						commond.setOptions(options.substring(0,options.length()-1).split(","));
					}
					commondList.add(commond);
				}
			}
		}
		else
			if(sheetName.equals("问答题"))
			{
				for(int i=2;i<sheet.getLastRowNum();i++)
				{
					if(PropertyUtil.objectNotEmpty(sheet.getRow(i)))
					{
						HSSFRow row = sheet.getRow(i);
						if(!PropertyUtil.objectNotEmpty(row.getCell(0))||getCellValue(row.getCell(0)).toString().equals(""))
						{
							continue;
						}
						QuestionBankValidCommond commond=new QuestionBankValidCommond();
						commond.setQuestionName(getCellValue(row.getCell(0)).toString());
						commond.setQuestionType("wendt");
						if(PropertyUtil.objectNotEmpty(row.getCell(1)))
						{
							String wordNumStr=getCellValue(row.getCell(1)).toString();
							Integer wordNum=new Integer(0);
							try
							{
								wordNum=Double.valueOf(wordNumStr).intValue();
							}
							catch(Exception e)
							{
								
							}
							if(wordNum.intValue()!=0)
							{
								commond.setWordNum(wordNum);
							}
						}
						commondList.add(commond);
					}
				}
			}
		return commondList;
	}
	/**
	 * 根据单元格数据类型返回相应数据
	 * 
	 * @param cell
	 * @return
	 */
	private Object getCellValue(Cell cell) 
	{
		switch (cell.getCellType()) 
		{
		case Cell.CELL_TYPE_STRING:
			return cell.getRichStringCellValue().toString();
		case Cell.CELL_TYPE_NUMERIC:
			Double d=new Double(cell.getNumericCellValue());
			if(d.toString().substring(d.toString().indexOf(".")+1).replace("0", "").equals(""))
			{
				return d.intValue();
			}
			return d.toString();
		case Cell.CELL_TYPE_BOOLEAN:
			return cell.getBooleanCellValue();
		case Cell.CELL_TYPE_FORMULA:
			return cell.getCellFormula();
		default:
			return "";
		}
	}
	
	/**
	 * @author RongSL
	 * @Date 2016-05-26
	 * 根据课程id找到相关班级id
	 * */
	@Override
	public String findClassId(QuestionnaireSurveyObjectValidCommond commond) throws Exception{
		return questionnaireDao.findClassId(commond);
	}
}
